<?php
// +----------------------------------------------------------------------
// | 杭州十禾信息科技有限公司
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2015 http://www.shelpe.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: LeePuman <ysyzlsm@163.com>
// +----------------------------------------------------------------------

	class Carine{
	
	
		protected $_php_service_url_prefix = NULL;
        protected $_java_service_url_prefix = NULL;
		protected $_auto_drive_service_prefix = NULL;        
        
		public function __construct(){
			//web service client init
			//automatic set the php services url
			if( defined('PHP_SERVICE_HOST') ) {
				$this->_php_service_url_prefix = PHP_SERVICE_HOST;
			}elseif($_SERVER['HTTP_HOST']){
				$this->_php_service_url_prefix = 'http://' . $_SERVER['HTTP_HOST'] . '/services/';
			}else{ // 客户端运行时，$_SERVER['HTTP_HOST']无值，必须手动给定
				$this->_php_service_url_prefix = JST_CLI_PHP_SERVICE_HOST;
			}
			 
			//java service
			if( !defined('JAVA_SERVICE_HOST') ){
				throw new NewzanException('JAVA_SERVICE_HOST配置信息丢失' , RetStatus::INNER_ERR);
			}
			$this->_java_service_url_prefix = JAVA_SERVICE_HOST;
			 
			//auto drive
			if( defined( 'AUTO_DRIVE_HOST') ){
				$this->_auto_drive_service_prefix = AUTO_DRIVE_HOST;
			}elseif($_SERVER['HTTP_HOST']){
				$this->_auto_drive_service_prefix = 'http://' . $_SERVER['HTTP_HOST'] . '/autodrive/';
			}else{ // 客户端运行时，$_SERVER['HTTP_HOST']无值，必须手动给定
				$this->_auto_drive_service_prefix = JST_CLI_AUTO_DRIVE_HOST;
			}
			
		}

        protected function httpRequest($url, $postFields = null, $curlOpts = null)
        {
        	$ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_FAILONERROR, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT , 600);
            //https 请求
            if(strlen($url) > 5 && strtolower(substr($url,0,5)) == "https" ) {
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
            }

            if (is_array($postFields) && 0 < count($postFields))
            {
                $postBodyString = "";
                $postMultipart = false;
                foreach ($postFields as $k => $v)
                {
                    if("@" != substr($v, 0, 1))//判断是不是文件上传
                    {
                        $postBodyString .= "$k=" . urlencode($v) . "&"; 
                    }
                    else//文件上传用multipart/form-data，否则用www-form-urlencoded
                    {
                        $postMultipart = true;
                    }
                }
                unset($k, $v);
                curl_setopt($ch, CURLOPT_POST, true);
                if ($postMultipart)
                {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
                }
                else
                {
                    curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString,0,-1));
                }
            }
            
            if($curlOpts) {
            	foreach($curlOpts as $opt => $val) {
            		curl_setopt($ch, $opt, $val);
            	}
            }
            
            $reponse = curl_exec($ch);
            if (curl_errno($ch))
            {
                throw new Exception(curl_error($ch),0);
            }
            else
            {
                $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
//                 Log::record('Carine::httpRequest() $httpStatusCode: ' . $httpStatusCode, Log::DEBUG);
                if (200 !== $httpStatusCode)
                {
                    throw new Exception("Carine::httpRequest()失败。返回值为： $reponse ", $httpStatusCode);
                }
            }
            curl_close($ch);
            return $reponse;
        }
        
        /**
         *  get the GET request url 
         *  @param string , $url
         *  @param mixed , params as a array
         *  @return string , the url  
         *  
         */
        
        public function httpGetRequest($url , $params){
    		//系统参数放入GET请求串
    		$requestUrl = $url . "?";
    		foreach ($params as $k => $v)
    		{
    			$requestUrl .= "$k=" . urlencode($v) . "&";
    		}
    		$requestUrl = substr($requestUrl, 0, -1);
    		return $this->httpRequest( $requestUrl );
        }
        
        
        /**
         *  get the average statics information for the keywords in a specific time slot on the whole Taobao website
         *  
         *  @param array(string) $words , a 1d array of words
         *  @param string $fields what kind of stats info needed ,
         *  					can be one or more as follow:
         *  					 pv, 展现量
         *                       avg_price, 平均点击价格
         *                       competition, 竞争度
         *                       click, 点击量
         *                       ctr, 点击率
         *                       area, 地域占比
         *
         *  @param date , $from , date('Y-m-d'), default to -8 days ago
         *  @param date , $to , date('Y-m-d'), default to yesterday
         *  @return mixed ,
         *  			array(
         *  				w1 => array(
         *  					'2012-12-01' => 12321
         *  					'2012-12-02' => 12321
         *  					...
         *  				),
         *  				...
         *  			)
         */
        public function getStatofWords($words, $fields='pv,avg_price,competition,click,ctr', $from = null , $to = null, $useApi = false){

        	$url = $this->_php_service_url_prefix . "keywordsstats";
        	$from = $from ? $from : date('Y-m-d' , strtotime('-7 day'));
        	$to = $to ? $to : date('Y-m-d' , strtotime('-1 day'));
        	$me = session('me');
        	$params  = array(
        			'keywords' => implode( ',', $words ),
        			'duration' => $from . ':' . $to,
        			'type' => 'avg',
        	        'use_api' => ($useApi ? 1 : 0),
        			'fields' => $fields,
        			'user_id' => $me['user_id'],
        	);

        
//         	Log::record('getStatofWords() parameters: ', Log::DEBUG);
//         	Log::record(json_encode($params), Log::DEBUG);
        	$resp = $this->httpRequest($url, $params);
        	return $resp;
        }
        
        /**
         *  get the trend for the keywords in a specific time slot
         *  @param mixed , $words , a 1d array of words
         *  @param string , what kind of stats info needed , 
         *  					can be one or more as follow:
         *  					 pv, 展现量 
         *                       avg_price, 平均点击价格
         *                       competition, 竞争度
         *                       click, 点击量
         *                       ctr, 点击率
         *                       area, 地域占比
		 *
         *  @param date , $from , date('Y-m-d'), default to -8 days ago
         *  @param date , $to , date('Y-m-d'), default to yesterday
         *  @return mixed , 
         *  			array(
         *  				w1 => array(
         *  					'2012-12-01' => 12321
         *  					'2012-12-02' => 12321
         *  					...
         *  				),
         *  				...
         *  			)
         */
        public function getTrendofWords($words, $fields='pv', $from = null , $to = null){
            $url = $this->_php_service_url_prefix . "keywordsstats";
            $from = $from ? $from : date('Y-m-d' , strtotime('-8 day'));
            $to = $to ? $to : date('Y-m-d' , strtotime('-1 day'));
            $me = session('me');
            $params  = array(
                    'keywords' => json_encode( $words ),
                    'duration' => $from . ':' . $to,
                    'type' => 'trend',
                    'fields' => $fields,
            		'user_id' => $me['user_id'],
                );
            $resp = $this->httpRequest( $url , $params);
            return $resp;
        }
        
        /* 
         * return the smart words
         * @param mixed , all the parammeters for reuest the smart words
         * @return mixed
         */

		public function getSmartWords($params){
            $url = $this->_php_service_url_prefix . "keywordsrcmm";
			$resp = $this->httpRequest($url , $params);
			// Log::record('-----------getSmartWords-----------', Log::DEBUG);
			// Log::record($resp, Log::DEBUG);
            return $resp;
			//return $this->_soapClient->__soapCall( 'services' , $data);
		}
        
        public function getFilterWords($params){
            $url = $this->_java_service_url_prefix . "keywordsfilter";
			$resp = $this->httpRequest($url , $params);
			// Log::record('-----------getFilterWords-----------', Log::DEBUG);
			// Log::record($resp, Log::DEBUG);
			return $resp;
        }
        
        public function getBondary($cid){
        	$me = session('me');
        	$url = $this->_php_service_url_prefix . "catemaxprops?cate_id=" . $cid . '&user_id=' . $me['user_id'];
  			$resp = $this->httpRequest($url);
  			$boundary = array();
            $result = json_decode($resp,true);
        	if($result['status'] == 200){
        		if(!empty($result["response"]["max"])){
        			$boundary = array();
        			foreach( $result["response"]["max"] as $k=>$v ){
        				$boundary[$k] = array(
        					'min' => 0,
        					'max' => $k == "ctr" ? round( floatval($v['max']) * 1000 ) : floatval($v['max'])
        				);
        				
        			}
        		}
                
        		return $boundary;
        	}else{
        	    return false;
        	}
                         	 
        }
        
        /**
         * 获取淘宝搜索相关词
         * @param string $word
         * @return mixed
         */
        public function getTaobaoSearchReleatedWords($word) {
        	$url = RELATED_SEARCH_URL_BASE . urlencode($word);
        	$resp = $this->httpRequest($url , null);
        	return $resp;
        }
        
        /**
         * 获取分词服务
         * @param string , the sentecens needed by segmented
         * @return array(string) , the words
         * 
         */
        public function segWords($text){
            $params = array(
                "text" => $text,
                "access_token" => 'haojiudian123'
            );
            $url = $this->_java_service_url_prefix . "WordSeg";
            $resp = $this->httpRequest($url, $params);
            $resp_action = json_decode($resp);
            if($resp_action) {
                $resp = array(
                        'status' => 200
                    );
                foreach ($resp_action as $key => $value) {
                    $resp['response'][] = $key;
                }
            }
            $resp = json_encode($resp);
            return $resp;
        }

        /**
         * 服务: 获取词语相关度
         * 
         * @param string $word 基准词.
         * @param array(string) $compWords 要比较的词列表
         * @param return array(word=>similarity) 返回结果是按similarity降序排列的.
         */
        public function wordSim($word, $compWords) {
       		if(!$compWords) { // no words to calculate
       			return array();
       		}
       		
       		$res = array();
       		foreach($compWords as $compWord){
       			$sim = similar_text($word, $compWord);
       			$res[$compWord] = $sim;
       		}
       		return $res;
        }
        
        public function syncRpt($modelClassName, $methodName, $params = array()) {
        	$me = session('me');
        	$manager = session('?manager') ? session('manager') : null;
        	$params = array(
        			'model' => $modelClassName,
        			'method' => $methodName,
        			'user_id' => $me['user_id'],
        			'access_token' => $manager ? $manager['oauth']['access_token'] : $me['oauth']['access_token'],
        			'params' => json_encode($params),
        	);

        	try{
        		$url = $this->_php_service_url_prefix . 'syncrpt';
        		$resp = $this->httpRequest($url , $params);
        	}catch(Exception $e){	
        		Log::record($e->getMessage());
        		Log::record($e->getTraceAsString());
        		return array( 'status' => 300 , 'response' => '内部网络错误') ;
        	}	
        	
        	return json_decode($resp , true);
        }
        
        /**
         * 启动给定的产品自动开车.
         * 
         * @param array(2D) $items 要立即启动初始化进程的产品. 格式为: array(array($product_id, $campaign_id))
         * @param string $is_sync 是否同步. 如果为true, 等待执行完毕才返回; 否则利用fast_cgi立即返回.
         * @return string 返回的字符串为"true", "false", 或者 错误信息.
         */
        public function startAutoProInit($items, $is_sync = false, $default_price = null) {
			$me = session('me');
			$manager = session('?manager') ? session('manager') : null;
			$params = array(
					'access_token' => $manager ? $manager['oauth']['access_token'] : $me['oauth']['access_token'],
					'items' => join_2d(',', '_', $items),
					'is_sync' => ($is_sync ? 1 : 0),
					'is_carine' => 1,
			);
			if($default_price > 0) {
               $params['custom_default_price'] = (int) $default_price;
            }
        	try{
        		$url = $this->_auto_drive_service_prefix . 'start';
        		Log::record('autodrive url: ' . $url . ', $params: ' . json_encode($params), Log::DEBUG);
        		$resp = $this->httpRequest($url , $params);
        		return $resp;
        		
        	} catch(Exception $e) {
        		Log::record($e->getMessage(), Log::ERR);
        		return '内部网络错误';
        	}
        }
	}
